package com.xinli.business.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ijpay.core.utils.DateTimeZoneUtil;
import com.xinli.business.domain.*;
import com.xinli.business.service.*;
import com.xinli.business.service.impl.FtMemberServiceImpl;
import com.xinli.common.annotation.Excel;
import com.xinli.common.annotation.RepeatSubmit;
import com.xinli.common.core.controller.BaseController;
import com.xinli.common.core.domain.AjaxResult;
import com.xinli.common.core.domain.entity.SysDictData;
import com.xinli.common.core.page.TableDataInfo;
import com.xinli.common.utils.*;
import com.xinli.pay.wxpay.OrderStatus;
import com.xinli.system.service.ISysDictDataService;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 小程序接口
 */
@RestController
@RequestMapping("/webApi")
public class TWebApiController extends BaseController {


    @Autowired
    private ITConfigService tConfigService;


    @Autowired
    private ITGuideService tGuideService;


    @Autowired
    private ITTwxxService tTwxxService;

    @Autowired
    private ITOrderService tOrderService;

    @Autowired
    private YzCodeUtils yzCodeUtils;

    @Autowired
    private IFtMemberService memberService;



    @Autowired
    private ISysDictDataService iSysDictDataService;


    @Autowired
    private ILfNoticeService lfNoticeService;


    @Autowired
    private ITLbImageService lbImageService;

    @Autowired
    private  MeetingReservationClient  meetingReservationClient;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取广告栏目
     */
    @GetMapping("/getLbImage")
    public   AjaxResult  getLbImage(TLbImage  vo){
        List<TLbImage> tLbImages = lbImageService.selectTLbImageList(vo);
        return AjaxResult.success(tLbImages);
    }

    /**
     * 发送消息
     */
    @PostMapping("/addNotice")
    @RepeatSubmit
    public   AjaxResult  addNotice(@RequestBody  LfNotice vo){
        vo.setSenderId(SecurityUtils.getUserId());
        lfNoticeService.insertLfNotice(vo);
        return  AjaxResult.success(vo.getId());
    }


    /**
     * 单条消息 ---设置成消息已读
     */
    @PostMapping("/updateNoticeRead")
    public   void  updateNoticeRead(@RequestBody  LfNotice vo){
        LfNotice byId = lfNoticeService.getById(vo.getId());
        byId.setIsRead(1);
        lfNoticeService.updateById(byId);
    }


    /**
     * 咨询师对话消息 ---设置成消息已读
     */
    @PostMapping("/updateBathNoticeRead")
    public   AjaxResult  updateBathNoticeRead(@RequestBody  LfNotice vo){
        Long receiverId = vo.getReceiverId();
        QueryWrapper<LfNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper
                .eq("sender_id", SecurityUtils.getUserId())
                .eq("receiver_id", receiverId)
        ).or(wrapper -> wrapper
                .eq("sender_id", receiverId)
                .eq("receiver_id", SecurityUtils.getUserId()
                ));
        queryWrapper.eq("type","2");
        List<LfNotice> list = lfNoticeService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            LfNotice lfNotice = list.get(i);
            lfNotice.setIsRead(1);
            lfNoticeService.updateById(lfNotice);
        }
        return  AjaxResult.success();
    }


    /**
     * 查询消息列表
     */
    @GetMapping("/getNoticeList")
    public   TableDataInfo  getNoticeList( LfNotice vo){
        startPage();
        if("1".equals(vo.getType())){
            vo.setReceiverId(SecurityUtils.getUserId());
            List<LfNotice> lfNotices = lfNoticeService.selectLfNoticeList(vo);
            return getDataTable(lfNotices);
        }else{
            vo.setSenderId(SecurityUtils.getUserId());
            // lfNotices
            List<LfNotice> lfNoticesmember = lfNoticeService.selectLfNoticeMemberList(vo);
            for (int i = 0; i < lfNoticesmember.size(); i++) {
                LfNotice lfNotice = lfNoticesmember.get(i);
                Long receiverId = lfNotice.getReceiverId();
                QueryWrapper<LfNotice> queryWrapper = new QueryWrapper<>();
                queryWrapper.and(wrapper -> wrapper
                        .eq("sender_id", SecurityUtils.getUserId())
                        .eq("receiver_id", receiverId)
                ).or(wrapper -> wrapper
                        .eq("sender_id", receiverId)
                        .eq("receiver_id", SecurityUtils.getUserId()
                ));
                queryWrapper.eq("type","2");
                queryWrapper.orderByDesc("create_time");
                // 一条数据
                queryWrapper.last("limit 1");
                List<LfNotice> lfNoticesRe = lfNoticeService.list(queryWrapper);
                lfNoticesmember.get(i).setLastNotice(CollUtil.isEmpty(lfNoticesRe)? null:lfNoticesRe.get(0));
            }
            return getDataTable(lfNoticesmember);

        }

    }


    /**
     * 查询消息详情
     */
    @GetMapping("/getNoticeDetail")
    public   AjaxResult  getNoticeDetail( LfNotice vo){
        LfNotice lfNotice1 = lfNoticeService.selectLfNoticeById(vo.getId());
        return AjaxResult.success(lfNotice1);
    }


    /**
     * 查询消息对话历史记录
     */
    @GetMapping("/getNoticeHistory")
    public   AjaxResult  getNoticeHistory( LfNotice vo){
        vo.setReceiverId(vo.getReceiverId());
        vo.setSenderId(SecurityUtils.getUserId());
        vo.setType("2");
        List<LfNotice> lfNotices = lfNoticeService.selectLfNoticeList(vo);
        return AjaxResult.success(lfNotices);
    }


    /**
     * 系统配置
     */
    @GetMapping("/nologin/getConfig")
    public AjaxResult getConfig() {
        TConfig tConfig = new TConfig();
        List<TConfig> tConfigs = tConfigService.selectTConfigList(tConfig);
        return AjaxResult.success(tConfigs);
    }


    /**
     * 指南列表
     */
    @GetMapping("/getGuideList")
    public TableDataInfo getGuideList(TGuide tGuide) {
        startPage();
        List<TGuide> list = tGuideService.selectTGuideList(tGuide);
        return getDataTable(list);
    }

    /**
     * 协议信息
     */
    @GetMapping("/nologin/getXyxx")
    public AjaxResult getXyxx(TTwxx tTwxx) {
        List<TTwxx> list = tTwxxService.selectTTwxxList(tTwxx);
        if (!CollUtil.isEmpty(list)) {
            return AjaxResult.success(list.get(0));
        }
        return AjaxResult.success();
    }


    /**
     * 创建订单生成订单号
     */
    @PostMapping("/createOrder")
    @RepeatSubmit
    public AjaxResult createOrder(@RequestBody OrderVO vo) {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        FtMember member = memberService.selectFtMemberByMemberId(Long.valueOf(vo.getZxsId()));
        if(member ==null){
            return AjaxResult.error("咨询师不存在");
        }
        String orderNumber = String.valueOf(snowflake.nextId());
        //生成订单
        TOrder orderInfo = new TOrder();
        // 商户订单编号
        orderInfo.setOrderNo(orderNumber);
        // 用户id
        orderInfo.setUserId(SecurityUtils.getUserId() + "");
        // 支付产品id
        orderInfo.setZxsId(vo.getZxsId());
        BigDecimal totalFee = member.getPrice();
        // 咨询开始时间
        orderInfo.setStartDate(vo.getStartDate());
        // 咨询结束时间
        orderInfo.setEndDate(vo.getEndDate());
        // 保存元
        orderInfo.setTotalPrice(totalFee);
        if(totalFee==null){
            totalFee=BigDecimal.ZERO;
        }
        if(totalFee.compareTo(BigDecimal.ZERO) == 0){
            orderInfo.setOrderStatus(OrderStatus.SUCCESS.getType());
        }else{
            // 未支付
            orderInfo.setOrderStatus(OrderStatus.NOTPAY.getType());
            // 没有支付过
            orderInfo.setIsPayed("0");
        }
        // 下单时间
        orderInfo.setOrderTime(DateUtil.date());
        //
        orderInfo.setRefundStatus(null);
        // 插入订单表
        tOrderService.save(orderInfo);
        if(totalFee.compareTo(BigDecimal.ZERO) == 0){
            log.info("发送消息-----------开始");
            LfNotice lfNotice =new LfNotice();
            lfNotice.setSenderId(Long.valueOf(orderInfo.getUserId()));
            lfNotice.setReceiverId(Long.valueOf(orderInfo.getZxsId()));
            lfNotice.setContentType("1");
            lfNotice.setInformation("您当前有一个预约需要处理");
            lfNotice.setType("4");
            lfNotice.setExtId(orderInfo.getId());
            lfNoticeService.insertLfNotice(lfNotice);
            log.info("发送消息-----------结束");
            this.createMeet(orderInfo);
        }
        return AjaxResult.success(orderInfo);
    }

    @Async
    public void createMeet(TOrder tOrder) {
        log.info("开始创建会议-----------开始====================");
        String  meetingtitle = "咨询预约";
        String startTime = DateUtil.format(tOrder.getStartDate(), "yyyy-MM-dd HH:mm:ss");
        String endTime = DateUtil.format(tOrder.getEndDate(), "yyyy-MM-dd HH:mm:ss");
        String zxsId = tOrder.getZxsId();
        String userId = tOrder.getUserId();
        FtMember member = ftMemberService.selectFtMemberByMemberId(Long.valueOf(zxsId));
        // 邀请人
        Inviter inviter = new Inviter(member.getNickName(), "", member.getPhone());

        FtMember user = ftMemberService.selectFtMemberByMemberId(Long.valueOf(userId));
        // 被邀请人
        Invitee invitee = new Invitee(user.getNickName(), "", user.getPhone());
        String meetInfo = meetingReservationClient.reserveMeeting(meetingtitle, startTime, endTime, inviter, invitee);
        log.info("创建会议-----------结束===================="+meetInfo);
        tOrder.setMeetInfo(meetInfo);
        tOrderService.updateTOrder(tOrder);
        log.info("更新订单会议信息-----------结束====================");
    }

    /**
     * 发送验证码
     */
    @RepeatSubmit
    @PostMapping(value = "/nologin/sendPhoneCode")
    public AjaxResult sendPhoneCode(@RequestParam(name = "phone", required = true) String phone) {
        Boolean aBoolean = yzCodeUtils.sendPhoneCode(phone);
        if (aBoolean) {
            return AjaxResult.success("发送成功");
        } else {
            return AjaxResult.error("发送失败");
        }
    }




    //-------------------问答/科普---------------------------

    @Autowired
    private ITQuestionService tQuestionService;

    @Autowired
    private ITQuestionReplyService questionReplyService;

    @Autowired
    private ITQuestionFollowService questionFollowService;


    /**
     * 专业问答列表
     */
    @GetMapping("/getQuestionList")
    public  TableDataInfo getQuestionList(LfPost vo) {
        List<Long> topicIds = topicService.getTopicIds(1);
        vo.setTopicIdArray(topicIds);
        startPage();
        // 相似问题
        String expostId = vo.getExpostId();
        if(!StringUtils.isEmpty(expostId)){
            vo.setExpostId(expostId);
        }
        List<LfPost> list = postService.selectLfPostList(vo);
        for (int i = 0; i < list.size(); i++) {
            postService.setViewAndReplyCountAndReList(list.get(i),"");
        }
        return getDataTable(list);
    }

    /**
     * 公益解答----咨询师回复过的
     */
    @GetMapping("/getGyjdQuestionList")
    public  TableDataInfo getGyjdQuestionList(LfPost vo) {
        LfPost  lfPost =new LfPost();
        List<Long> topicIds = topicService.getTopicIds(1);
        lfPost.setTopicIdArray(topicIds);
        startPage();
        vo.setZxsId(vo.getZxsId());
        List<LfPost> list = postService.selectLfPostList(lfPost);
        for (int i = 0; i < list.size(); i++) {
            postService.setViewAndReplyCountAndReList(list.get(i),  vo.getZxsId());
        }
        return getDataTable(list);
    }

    /**
     * 问题详情
     */
    @GetMapping("/getQuestionDetail")
    public AjaxResult getQuestionDetail(LfPost vo) {
        LfPost question = postService.selectLfPostById(vo.getId());
//        if (question == null) {
//            return AjaxResult.error("问题不存在");
//        }
        postService.setViewAndReplyCount(question);
        // 查看数量加1
        postService.updateViewCount(question);
        return AjaxResult.success(question);
//        return  AjaxResult.success(question);
    }



    @Autowired
    private ITZxsFollowService tZxsFollowService;
    @Autowired
    private ILfCommentThumbsService commentThumbsService;



    /**
     * 全部回答  传 postId 和 回答的Id(pid)
     */
    @GetMapping("/getQuestionReplyList")
    public TableDataInfo getQuestionReplyList(LfComment   vo) {
        startPage();
        vo.setType(Long.valueOf(1));
        vo.setPid(Long.valueOf(0));
        List<LfComment> list = lfcommentService.selectLfCommentList(vo);
        for (int i = 0; i < list.size(); i++) {
            //是否关注
            lfcommentService.setQuestionReplyCount(list.get(i));
            Long uid = list.get(i).getUid();
            Long id = list.get(i).getId();
            // 是否关注
            Boolean aBoolean = tZxsFollowService.isfollowZxs(uid+"");
            list.get(i).setIsFollow(aBoolean);
            // 是否点赞
            list.get(i).setIsDz(commentThumbsService.isDz(id));
            // 点赞数量
            list.get(i).setDzCount(commentThumbsService.dzCount(id));
        }
        return getDataTable(list);
    }



    /**
     * 发表评论
     */
    @PostMapping("/addComment")
    @RepeatSubmit
    public AjaxResult addComment(@Validated  @RequestBody  LfComment   vo) {
        vo.setUid(SecurityUtils.getUserId());
        vo.setCreateTime(DateUtils.getNowDate());
        lfcommentService.insertLfComment(vo);
        return AjaxResult.success();
    }



    /**
     * 全部评论
     */
    @GetMapping("/getQuestionReplyPlList")
    public AjaxResult getQuestionReplyPlList(LfComment   vo) {
        startPage();
        vo.setType(Long.valueOf(2));
        List<LfComment> list = lfcommentService.selectLfCommentList(vo);
        for (int i = 0; i < list.size(); i++) {
            LfComment lfComment = list.get(i);
            Long id = lfComment.getId();
            LfComment  reply = new LfComment();
            reply.setPid(id);
            List<LfComment> lfComments = lfcommentService.selectLfCommentList(reply);
            list.get(i).setReplyList(lfComments);
        }
        return AjaxResult.success(list);
    }



    @Autowired
    private ILfPostService  postService;


    @Autowired
    private ILfTopicService  topicService;

    @Autowired
    private ILfCommentService  lfcommentService;






    /**
     * 获取圈子列表
     */
    @GetMapping("/getTopicList")
    public   TableDataInfo getTopicList(LfTopic  vo) {
        startPage();
        List<LfTopic> topics = topicService.selectLfTopicList(vo);
        return  getDataTable(topics);
    }

    /**
     * 获取科普文章列表
     */
    @GetMapping("/getPostList")
    public  TableDataInfo getPostList(LfPost  vo) {

        List<Long> topicIds = this.getTopicIds(2);
        vo.setTopicIdArray(topicIds);
        startPage();
        List<LfPost> posts = postService.selectLfPostList(vo);
        return  getDataTable(posts);
    }



    /**
     * 获取科普文章详情
     */
    @GetMapping(value = "/getkpwz/{id}")
    public AjaxResult getkpwz(@PathVariable("id") Long id)
    {
        return AjaxResult.success(postService.selectLfPostById(id));
    }




    public List<Long> getTopicIds(int   cateId   ){
        LfTopic  lfTopic = new LfTopic();
        lfTopic.setCateId(Long.valueOf(cateId));
        List<LfTopic> topics = topicService.selectLfTopicList(lfTopic);
        List<Long> topicIds = topics.stream().map(item->item.getId()).collect(Collectors.toList());
        return topicIds;
    }


    @Autowired
    private ITOrderPjService  orderPjService;

    @Autowired
    private IFtMemberService  ftMemberService;



    /**
     * 咨询师评价信息(分页)
     */
    @GetMapping("/getOrderPjList")
    public  TableDataInfo getOrderPjList(TOrderPj  vo) {
        startPage();
        // 显示
        vo.setStatus("1");
        List<TOrderPj> tOrderPjs = orderPjService.selectTOrderPjList(vo);
        return  getDataTable(tOrderPjs);
    }

    /**
     * 咨询师列表信息(分页)
     */
    @GetMapping("/getMemberList")
    public  TableDataInfo getMemberList(FtMember member){
        startPage();
        List<FtMember> ftMembers = memberService.selectFtMemberListApp(member);
        return  getDataTable(ftMembers);
    }


    @Autowired
    private IConsultantApplicationService consultantApplicationService;


    /**
     * 咨询师详情
     */
    @GetMapping("/getMemberDetail/{memberId}")
    public  AjaxResult  getMemberDetail(@PathVariable("memberId" ) Long memberId){
        FtMember member = memberService.selectFtMemberByMemberId(memberId);
        if(member==null){
            throw new RuntimeException("用户不存在");
        }
        // 从业年限
        int yearsOfExperience = consultantApplicationService.getYearsOfExperience(memberId);
        member.setYearsOfExperience(yearsOfExperience+"");
        // 查询审核记录
        QueryWrapper<ConsultantApplication>   queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",memberId);
        queryWrapper.eq("status",1);
        List<ConsultantApplication> checklist = consultantApplicationService.list(queryWrapper);
        member.setCheckList(checklist);
        QueryWrapper<TOrder>     queryWrapperorder = new QueryWrapper<>();
        queryWrapperorder.eq("zxs_id",memberId);
        queryWrapperorder.eq("order_status","3");
        long count = tOrderService.count(queryWrapperorder);
        member.setOrderNum(count);
        return  AjaxResult.success(member);
    }


    @Autowired
    private ITTsydService tTsydService;


    /**
     * 获取特殊约定列表
     */
    @GetMapping("/nologin/getTsydList")
    public    AjaxResult getTsydList(TTsyd tTsyd){
        List<TTsyd> tTsyds = tTsydService.selectTTsydListApp(tTsyd);
        return  AjaxResult.success(tTsyds);
    }


    /**
     * 查询数据字典
     */
    @GetMapping("/getDict")
    public AjaxResult getDict(String key) {
        SysDictData sysDictData= new SysDictData();
        sysDictData.setDictType(key);
        List<SysDictData> dictCache = iSysDictDataService.selectDictDataList(sysDictData);
        return AjaxResult.success(dictCache);
    }

    @Autowired
    private IConsultantTimeSlotService consultantTimeSlotService;

    /**
     * 获取预约时间
     */
    @GetMapping("/getTimeSolt")
    public AjaxResult getTimeSolt(String userId) {
        QueryWrapper<ConsultantTimeSlot> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.in("status", Arrays.asList("1", "2"));

        List<ConsultantTimeSlot> consultantTimeSlots = consultantTimeSlotService.list(queryWrapper);

        // 使用 Java Stream 分组 + 排序
        Map<String, List<ConsultantTimeSlot>> result = consultantTimeSlots.stream()
                .collect(Collectors.groupingBy(
                        // 按 slotDate 格式化为 yyyy-MM-dd 分组
                        slot -> DateUtils.parseDateToStr("yyyy-MM-dd", slot.getSlotDate()),
                        // 每个分组内部按 startTime 的“时间”部分排序
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                    list.sort(Comparator.comparing((ConsultantTimeSlot slot) -> {
                                        Calendar cal = Calendar.getInstance();
                                        cal.setTime(slot.getStartTime());
                                        cal.set(Calendar.YEAR, 0);
                                        cal.set(Calendar.MONTH, 0);
                                        cal.set(Calendar.DAY_OF_MONTH, 0);
                                        return cal.getTime();
                                    }));
                                    return list;
                                }
                        )
                ));

        return AjaxResult.success(result);
    }


    @Autowired
    private  ITYjfkService  yjfkService;




    /**
     * 意见反馈
     */
    @PostMapping("/yjfk")
    @RepeatSubmit
    public AjaxResult yjfk(@RequestBody TYjfk tYjfk)
    {
        tYjfk.setUserId(getUserId().toString());
        return toAjax(yjfkService.save(tYjfk));
    }


    /**
     * 查询所有的咨询师
     */
    @GetMapping("/getALlMemeberLilst")
    public  TableDataInfo  getALlMemeberLilst(){
        startPage();
        List<FtMember> ftMembers = memberService.selectFtMemberList(null);
        return    getDataTable(ftMembers);
    }




}
